package com.yikes.srb.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yikes.srb.common.enums.ResultCodeEnum;
import com.yikes.srb.common.result.PageResult;
import com.yikes.srb.common.utils.object.BeanUtils;
import com.yikes.srb.leadingModle.form.borrowinfo.BorrowInfoAddForm;
import com.yikes.srb.leadingModle.form.borrowinfo.BorrowInfoApprovalForm;
import com.yikes.srb.leadingModle.form.borrowinfo.BorrowInfoEditForm;
import com.yikes.srb.leadingModle.form.borrowinfo.BorrowInfoQuery;
import com.yikes.srb.leadingModle.vo.BorrowInfoVO;
import com.yikes.srb.leadingModle.vo.BorrowerDetailVO;
import com.yikes.srb.mapper.IntegralGradeMapper;
import com.yikes.srb.mapper.UserInfoMapper;
import com.yikes.srb.pojo.entity.BorrowInfo;
import com.yikes.srb.mapper.BorrowInfoMapper;
import com.yikes.srb.pojo.entity.Borrower;
import com.yikes.srb.pojo.entity.IntegralGrade;
import com.yikes.srb.pojo.entity.UserInfo;
import com.yikes.srb.pojo.enums.BorrowInfoStatusEnum;
import com.yikes.srb.pojo.enums.BorrowerStatusEnum;
import com.yikes.srb.pojo.enums.ServiceWorkCodeEnum;
import com.yikes.srb.pojo.enums.UserBindEnum;
import com.yikes.srb.service.BorrowInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yikes.srb.service.BorrowerService;
import com.yikes.srb.service.DictService;
import com.yikes.srb.service.LendService;
import com.yikes.srb.web.utils.As;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author guanrong.yin
 * @since 2024-12-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    private final UserInfoMapper userInfoMapper;

    private final IntegralGradeMapper integralGradeMapper;

    private final BorrowerService borrowerService;

    private final DictService dictService;

    private final LendService lendService;

    @Override
    public PageResult<BorrowInfoVO> listPage(BorrowInfoQuery query) {

        IPage<BorrowInfo> page = baseMapper.selectBorrowInfoPage(Page.of(query.getPageNum(), query.getPageSize()), query);

        if (CollUtil.isEmpty(page.getRecords())) {
            return PageResult.build(page.getTotal(), page.getPages(), CollUtil.empty(List.class));
        }

        List<BorrowInfoVO> list = Lists.newArrayList();
        for (BorrowInfo record : page.getRecords()) {

            BorrowInfoVO bean = BeanUtils.toBean(record, BorrowInfoVO.class);
            // 组装数据
            String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", record.getReturnMethod());
            String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", record.getMoneyUse());
            String status = BorrowInfoStatusEnum.getMsgByStatus(record.getStatus());
            bean.setReturnMethod(returnMethod);
            bean.setMoneyUse(moneyUse);
            bean.setStatus(status);

            list.add(bean);
        }

        return PageResult.build(page.getTotal(), page.getPages(), list);

    }

    @Override
    public BorrowInfoVO infoId(Long id) {

        BorrowInfo borrowInfo = getById(id);
        BorrowInfoVO bean = BeanUtils.toBean(borrowInfo, BorrowInfoVO.class);
        return bean;

    }

    @Override
    public void create(BorrowInfoAddForm form) {

        BorrowInfo bean = BeanUtils.toBean(form, BorrowInfo.class);
        save(bean);
    }

    @Override
    public void edit(BorrowInfoEditForm form) {

        BorrowInfo bean = BeanUtils.toBean(form, BorrowInfo.class);
        updateById(bean);
    }

    @Override
    public void del(Long id) {

        baseMapper.deleteById(id);
    }


    @Override
    public BigDecimal getBorrowAmount(Long userId) {

        //获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        As.isNotNull(userInfo, ResultCodeEnum.USER_NOT_EXIST);
        Integer integral = userInfo.getIntegral();

        //根据积分查询借款额度
        QueryWrapper<IntegralGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("integral_start", integral);
        queryWrapper.ge("integral_end", integral);
        IntegralGrade integralGradeConfig = integralGradeMapper.selectOne(queryWrapper);

        if (integralGradeConfig == null) {
            return new BigDecimal("0");
        }
        return integralGradeConfig.getBorrowAmount();
    }

    @Override
    public void saveBorrowInfo(BorrowInfoAddForm form, Long userId) {

        //获取userInfo的用户数据
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //判断用户绑定状态
        As.isTure(
                userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus().intValue(),
                ServiceWorkCodeEnum.USER_NO_BIND_ERROR);

        //判断用户信息是否审批通过
        As.isTure(
                userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),
                ServiceWorkCodeEnum.USER_NO_AMOUNT_ERROR);

        //判断借款额度是否足够
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        As.isTure(
                form.getAmount().doubleValue() <= borrowAmount.doubleValue(),
                ServiceWorkCodeEnum.USER_AMOUNT_LESS_ERROR);

        //存储数据
        BorrowInfo borrowInfo = BeanUtils.toBean(form, BorrowInfo.class);
        borrowInfo.setUserId(userId);
        //百分比转成小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        baseMapper.insert(borrowInfo);

    }

    @Override
    public Integer getStatusByUserId(Long userId) {

        QueryWrapper<BorrowInfo> borrowInfoQueryWrapper = new QueryWrapper<>();
        borrowInfoQueryWrapper.select("status").eq("user_id", userId);
        List<Object> objects = baseMapper.selectObjs(borrowInfoQueryWrapper);

        if (objects.isEmpty()) {
            //借款人尚未提交信息
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        return (Integer) objects.get(0);
    }

    @Override
    public Map<String, Object> getBorrowInfoDetail(Long id) {

        // 查询借款对象
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        BorrowInfoVO bean = BeanUtils.toBean(borrowInfo, BorrowInfoVO.class);
        // 组装数据
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        bean.setReturnMethod(returnMethod);
        bean.setMoneyUse(moneyUse);
        bean.setStatus(status);

        // 根据user_id获取借款人对象
        Borrower borrower = borrowerService.lambdaQuery().eq(Borrower::getUserId, borrowInfo.getUserId()).one();
        // 组装借款人对象
        BorrowerDetailVO borrowerDetailVO = borrowerService.getBorrowerDetailVOById(borrower.getId());

        // 组装数据
        Map<String, Object> result = new HashMap<>();
        result.put("borrowInfo", bean);
        result.put("borrower", borrowerDetailVO);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approval(BorrowInfoApprovalForm form) {

        //修改借款信息状态
        Long borrowInfoId = form.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        borrowInfo.setStatus(form.getStatus());
        baseMapper.updateById(borrowInfo);

        //审核通过则创建标的
        if (form.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()) {
            //创建标的
            lendService.createLend(form, borrowInfo);
        }

    }

}
